package myself.doit.schedule.v1;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.UndeclaredThrowableException;

/**
 * Created by bjliuyong on 2017/1/10.
 */
public class ScheduledMethodRunnable implements Runnable {

    private final Object target;

    private final Method method;


    public ScheduledMethodRunnable(Object target, Method method) {
        this.target = target;
        this.method = method;
    }

    public ScheduledMethodRunnable(Object target, String methodName) throws NoSuchMethodException {
        this.target = target;
        this.method = target.getClass().getMethod(methodName);
    }


    public Object getTarget() {
        return this.target;
    }

    public Method getMethod() {
        return this.method;
    }


    @Override
    public void run() {
        try {

            if((!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers())) && !method.isAccessible()) {
                method.setAccessible(true);
            }
            this.method.invoke(this.target);
        }
        catch (InvocationTargetException ex) {
            throw new UndeclaredThrowableException(ex) ;
        }
        catch (IllegalAccessException ex) {
            throw new UndeclaredThrowableException(ex);
        }
    }

}
